package com.atguigu.spzx.user.service.impl;



import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.util.HttpUtils;
import com.atguigu.spzx.model.entity.user.UserInfo ;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.common.util.RegexValidateUtils;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.SmsService;
import jakarta.annotation.Resource;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendCode(String mobile) {
        //1、校验手机号格式
        boolean b = RegexValidateUtils.checkCellphone(mobile);
        if(!b){
            //手机号码格式错误
            throw new GuiguException(ResultCodeEnum.MOBILE_ERROR);
        }
        //2、验证获取验证码频率: 2分钟内不能重复获取验证码、1天内只能获取5次
        String limitKey = "user:code:limit:"+ mobile;
        String countKey = "user:code:count:"+mobile;
        if(stringRedisTemplate.hasKey(limitKey)){
            //2分钟内获取过验证码
            throw new GuiguException(ResultCodeEnum.SEND_MSG_LIMIT_ERROR);
        }
        String countStr = stringRedisTemplate.opsForValue().get(countKey);
        if(StringUtils.hasLength(countStr)){
            if(Integer.parseInt(countStr)>=5){
                //一天内获取验证码次数过多
                throw new GuiguException(ResultCodeEnum.SEND_MSG_COUNT_ERROR);
            }
        }



        //3、判断是否是重复注册
        UserInfo userInfo = userInfoMapper.findUserInfoByMobile(mobile);
        if(userInfo!=null){
            throw new GuiguException(ResultCodeEnum.MOBILE_EXISTS_ERROR);
        }

        //4、生成验证码 发送
        String code = RandomUtil.randomNumbers(4);
        boolean sendMsg = sendMsg(code, mobile);
        if(!sendMsg){
            //短信发送失败
            throw new GuiguException(ResultCodeEnum.SEND_MSG_ERROR);
        }
        //5、如果发送成功 缓存验证码到redis中 、
        String codeKey = "user:regist:code:"+mobile;
        stringRedisTemplate.opsForValue().set(codeKey,code , 15, TimeUnit.MINUTES);
        //获取验证码的次数：
        Long count = stringRedisTemplate.opsForValue().increment(countKey);
        if(count==1){
            //第一次获取验证码成功 设置次数的key的过期时间为24小时
            stringRedisTemplate.expire(countKey , 1, TimeUnit.DAYS );
        }
        //2分钟不能重复获取：使用手机号拼接唯一的key存入 过期时间为2分钟
        stringRedisTemplate.opsForValue().set(limitKey , "1",2,TimeUnit.MINUTES);

    }

    //发送短信的业务代码
    private boolean sendMsg(String code,String mobile){
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        // 购买短信服务的用户的唯一标识
        String appcode = "8e45699f00ff4bdbb807664045acd813";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        //参数：
        // content表示要设置到短信模板中的内容  code标识 填充code的值  多参数使用逗号分开
        bodys.put("content", "code:"+code+",expire_at:15");
        //template_id表示模板id： 只有企业认证用户可以在平台中找客服申请自定义模板  测试只能使用默认的
        bodys.put("template_id", "CST_qozfh101");//CST_qozfh101   CST_ptdie100
        // 发送短信的手机号
        bodys.put("phone_number", mobile);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            //发送网络请求将短信发送参数传给 短信平台的短信接口
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            //解析短信发送的结果
            System.out.println(response.getStatusLine().getStatusCode());
            String result = EntityUtils.toString(response.getEntity());
            //result代表响应体json字符串
            Map map = JSON.parseObject(result, Map.class);
            String status = map.get("status").toString();
            if("OK".equals(status)){
                System.out.println("短信发送成功:"+result );
                return true;
            }else{
                System.out.println("短信发送失败:"+result );
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
